package com.zzy.filter;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.*;

/**
 * 使用 JSONObject 读取 数据库 使用 blob 存
 */
public class TypeHanderBlobJSONObject extends BaseTypeHandler<JSONObject> {


    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, JSONObject jsonObject, JdbcType jdbcType) throws SQLException {
        if(jsonObject==null){
            return;
        }
        ByteArrayInputStream bis = null;
        try {
            // 把 jsonObject 变成 字节流
            String s = JSONObject.toJSONString(jsonObject);
            bis = new ByteArrayInputStream(s.getBytes());
        } catch (Exception e) {
            throw new RuntimeException("bytes Error!");
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    throw new RuntimeException("bytes Error!");
                }
            }
        }
        preparedStatement.setBinaryStream(i, bis);
    }

    @Override
    public JSONObject getNullableResult(ResultSet resultSet, String s) throws SQLException {
        Blob blob = resultSet.getBlob(s);
        if(blob ==null ){
            return null;
        }
        String res = new String(blob.getBytes((long)1 , (int)blob.length() ));
        return JSONObject.parseObject(res);
    }

    @Override
    public JSONObject getNullableResult(ResultSet resultSet, int i) throws SQLException {
        Blob blob = resultSet.getBlob(i);
        if(blob ==null ){
            return null;
        }
        String res = new String(blob.getBytes((long)1 , (int)blob.length() ));
        return JSONObject.parseObject(res);
    }

    @Override
    public JSONObject getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        Blob blob = callableStatement.getBlob(i);
        if(blob ==null ){
            return null;
        }
        String res = new String(blob.getBytes((long)1 , (int)blob.length() ));
        return JSONObject.parseObject(res);
    }
}
